<template>
	<view class="page">
		<view class="tips"><text>tips：点击左边文字可以进行修改</text></view>
		<view class="row" >
			<view @click="reviseAvatar()">头像</view>
			<view class="avatar">
				<image :src="userInfo.avatarUrl" @click="preAvatar"></image>
			</view>
		</view>
		<view class="row" @click="setPageState(1)">
			<view>昵称</view>
			<view>{{userInfo.name}}</view>
		</view>
		<view class="revise-row" v-if="pageState === 1">
			<view>修改昵称：</view>
			<view><input v-model="nameInput" placeholder="输入新昵称" @confirm="nameConfirm" /></view>
		</view>
		<view class="row" @click="setPageState(2)">
			<view>邮箱</view>
			<view>{{userInfo.mail}}</view>
		</view>
		<view class="revise-row" v-if="pageState === 2">
			<view>修改邮箱：</view>
			<view><input v-model="mailInput" placeholder="输入新邮箱" @confirm="mailConfirm" /></view>
		</view>
		<view class="row" >
			<view  @click="reviseChat()">微信</view>
			<view class="avatar">
				<image :src="chatUrl"  @click="preChatUrl" ></image>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		useUserStore
	} from '../../stores/user';
	import {
		mapActions,
		mapState
	} from 'pinia';
	export default {
		computed: {
			...mapState(useUserStore, ['userInfo']),
		},
		async created() {
			const rhc = getApp().globalData.rhc
			const api = getApp().globalData.api
			const res = await uni.request({
				url: api + "/user/info/chatUrl",
				header: {
					'Cookie': rhc
				}
			})
			this.chatUrl = res.data.data
		},
		data() {
			return {
				pageState: 0, // 页面状态：0-无输入框，1-昵称修改框，2-邮箱修改框
				nameInput: "",
				mailInput: "",
				//联系方式（本人的微信号截图）
				chatUrl: ""
			}
		},
		methods: {
			...mapActions(useUserStore, ['fetchUserInfo']),
			setPageState(state) {
				this.pageState = this.pageState === state ? 0 : state;
			},
			preChatUrl(){
				const arr = [this.chatUrl]
				uni.previewImage({
					urls: arr
				})
			},
			//头像预览
			preAvatar(){
				const arr = [this.userInfo.avatarUrl]
				uni.previewImage({
					urls: arr
				})
			},
			
			//修改微信号图片
			async reviseChat() {
				const app = getApp();
				const thisPage = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //这里指定压缩图，默认二者都有	
					sourceType: ['album'], //从相册选择
					success: async function(res) {
						// console.log(JSON.stringify(res.tempFilePaths));
						console.log(res.tempFilePaths);
						const imagePath = res.tempFilePaths[0]; //图片临时地址
						console.log("图片临时地址为 " + imagePath)
						//获取扩展名
						const extension = imagePath.split('.').pop().toLowerCase();
						console.log("扩展名为" + extension)
						//判断是否为jpg jpeg png
						const myExtension = ['jpg', 'jpeg', 'png'];
						if (!myExtension.includes(extension)) {
							//如果不为	myExtension
							uni.showToast({
								title: '仅支持 jpg, jpeg, png',
								icon: 'none'
							})
							return;
						}
						//此时图片imagePath已经准备就绪
						// 1. 向后端请求上传 token
						const tokenResult = await uni.request({
							url: app.globalData.api + "/user/info/chatUrlToken",
							header: {
								'Cookie': app.globalData.rhc
							},
							data: {
								extension: extension
							}
						});
						console.log("后端传来的token： " + tokenResult.data.data.upToken)
						console.log("后端传来的key： " + tokenResult.data.data.key)
						const tokenResponse = tokenResult.data.data;
						const token = tokenResponse.upToken;
						const key = tokenResponse.key;
						uni.uploadFile({
							url: 'https://up.qiniup.com',
							filePath: imagePath,
							name: 'file',
							formData: {
								'token': token,
								'key': key
							},
							// 七牛云存成功后的回调
							success: async (uploadFileRes) => {
								// let data = uploadFileRes.data
								// let key = JSON.parse(uploadFileRes.data).key || timestamp;
								// let url = '七牛云访问图片的域名路径' + key
								console.log('七牛云响应：');
								console.log(uploadFileRes);
								if (uploadFileRes.statusCode == 200) {
									//上传成功后，再次 post(原来是get)请求
									//  地址 /info/chatUrl告诉后端上传成了，刷新头像
									const tokenResult = await uni.request({
										url: app.globalData.api + "/user/info/chatUrl",
										method: 'POST',
										header: {
											'Cookie': app.globalData.rhc,
											'content-type': 'application/json',
										},
										data: {
											// 请求体带上用户 key
											key: key
										},
										success: async (res) => {
											console.log("二次向后端请求成功：")
											console.log(res.data);
											thisPage.chatUrl = res.data.data
										}
									});
									//这里已经得到二次后端响应后
									uni.showToast({
										title: '微信名片更新成功',
										icon: 'none'
									})
								}
							},
							fail: (err) => {
								console.log(err)
							}
						});

					}
				})
			},
			//修改头像
			async reviseAvatar() {
				const app = getApp();
				const thisPage = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //这里指定压缩图，默认二者都有	
					sourceType: ['album'], //从相册选择
					success: async function(res) {
						// console.log(JSON.stringify(res.tempFilePaths));
						console.log(res.tempFilePaths);
						const imagePath = res.tempFilePaths[0]; //图片临时地址
						console.log("图片临时地址为 " + imagePath)
						//获取扩展名
						const extension = imagePath.split('.').pop().toLowerCase();
						console.log("扩展名为" + extension)
						//判断是否为jpg jpeg png
						const myExtension = ['jpg', 'jpeg', 'png'];
						if (!myExtension.includes(extension)) {
							//如果不为	myExtension
							uni.showToast({
								title: '仅支持 jpg, jpeg, png',
								icon: 'none'
							})
							return;
						}
						//此时图片imagePath已经准备就绪
						// 1. 向后端请求上传 token
						const tokenResult = await uni.request({
							url: app.globalData.api + "/user/info/avatar",
							header: {
								'Cookie': app.globalData.rhc
							},
							data: {
								extension: extension
							}
						});
						console.log("后端传来的token： " + tokenResult.data.data.upToken)
						console.log("后端传来的key： " + tokenResult.data.data.key)
						const tokenResponse = tokenResult.data.data;
						const token = tokenResponse.upToken;
						const key = tokenResponse.key;
						uni.uploadFile({
							url: 'https://up.qiniup.com',
							filePath: imagePath,
							name: 'file',
							formData: {
								'token': token,
								'key': key
							},
							// 七牛云存成功后的回调
							success: async (uploadFileRes) => {
								// let data = uploadFileRes.data
								// let key = JSON.parse(uploadFileRes.data).key || timestamp;
								// let url = '七牛云访问图片的域名路径' + key
								console.log('七牛云响应：');
								console.log(uploadFileRes);
								if (uploadFileRes.statusCode == 200) {
									//上传成功后，再次 post(原来是get)请求
									//  地址 /info/avatar告诉后端上传成了，刷新头像
									const tokenResult = await uni.request({
										url: app.globalData.api + "/user/info/avatar",
										method: 'POST',
										header: {
											'Cookie': app.globalData.rhc,
											'content-type': 'application/json',
										},
										data: {
											// 请求体带上用户 key
											key: key
										},
										success: async (res) => {
											console.log("二次向后端请求成功：")
											console.log(res.data);
											await thisPage.fetchUserInfo(app.globalData.api, app.globalData.rhc);
										}
									});
									//这里已经得到二次后端响应后
									uni.showToast({
										title: '头像更新成功',
										icon: 'none'
									})
								}
							},
							fail: (err) => {
								console.log(err)
							}
						});
					}
				});
			},
			//修改昵称
			async nameConfirm(event) {
				const app = getApp();
				const thisPage = this;
				const newName = event.detail.value; //修改后的名字
				console.log("昵称js本地修改为: " + newName)
				await uni.request({
					url: app.globalData.api + "/user/info/name",
					method: 'POST',
					header: {
						'Cookie': app.globalData.rhc,
						'content-type': 'application/json',
					},
					data: {
						// 请求体带上用户 newName
						newName: newName
					},
					success: async (res) => {
						console.log("昵称修改成功")
						console.log(res.data);
						await thisPage.fetchUserInfo(app.globalData.api, app.globalData.rhc);
					}
				});
				//这里已经改好了昵称
				uni.showToast({
					title: '昵称更新成功',
					icon: 'none'
				})
			},
			//修改邮箱
			async mailConfirm(event) {
				const app = getApp();
				const thisPage = this;
				const newMail = event.detail.value; //修改后的名字
				console.log("昵邮箱s本地修改为: " + newMail)
				await uni.request({
					url: app.globalData.api + "/user/info/mail",
					method: 'POST',
					header: {
						'Cookie': app.globalData.rhc,
						'content-type': 'application/json',
					},
					data: {
						// 请求体带上用户 newMail
						newMail: newMail
					},
					success: async (res) => {
						console.log("邮箱修改成功")
						console.log(res.data);
						await thisPage.fetchUserInfo(app.globalData.api, app.globalData.rhc);
					}
				});
				//这里已经改好了邮箱
				uni.showToast({
					title: '邮箱更新成功',
					icon: 'none'
				})
			}
		}
	}
</script>

<style>
	.page {
		padding: 12rpx 20rpx;
		background-color: #f6f6f6;
	}

	.tips {
		font-size: 26rpx;
		margin: 0 0 10rpx 10rpx;
	}


	.row {
		background-color: #ffffff;
		height: 40rpx;
		font-size: 32rpx;
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		margin-bottom: 10rpx;
		border-radius: 20rpx;
		/* 添加底部边框分隔线 */
	}

	.revise-row {
		background-color: #ededed;
		height: 40rpx;
		font-size: 32rpx;
		display: flex;
		justify-content: start;
		padding: 20rpx;
		margin-bottom: 10rpx;
		border-radius: 20rpx;
	}

	.avatar {
		width: 60rpx;
		height: 60rpx;
	}

	.avatar image {
		width: 100%;
		height: 100%;
	}
</style>